package xin.luna.structs;

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

import java.util.Iterator;

public class StackLinkedTable<Item> implements Iterable<Item> {
  private Node head;

  private int length;

  public static void main(String[] args) {
    StackLinkedTable<String> s = new StackLinkedTable<>();
    while (!StdIn.isEmpty()) {
      String item = StdIn.readString();
      if (!item.equals("-")) {
        s.push(item);
      } else if (!s.isEmpty()) {
        StdOut.print(s.pop() + "   ");
      }
    }

    StdOut.println("(" + s.size() + " left on stack)");
  }

  public boolean isEmpty() {
    return 0 == length;
  }

  public int size() {
    return length;
  }

  public boolean isFull() {
    return false;
  }

  public void push(Item item) {
    Node node = new Node();
    node.item = item;
    node.next = head;
    head = node;
    length++;
  }

  public Item peek() {
    return head.item;
  }

  public Item pop() {
    length--;
    Node node = head;
    head = node.next;

    return node.item;
  }

  @Override
  public Iterator<Item> iterator() {
    return new StackLinkedIterator();
  }

  private class Node {
    private Item item;

    private Node next;
  }

  private class StackLinkedIterator implements Iterator<Item> {

    private Node node = head;

    @Override
    public boolean hasNext() {
      return null != node;
    }

    @Override
    public Item next() {
      Node item = node;
      node = node.next;
      return item.item;
    }
  }
}
